const util = require('util');
const simpleGit = require('simple-git');
const childProcess = require('child_process');
const package = require('../package.json');
const chalk = require('chalk');

const cwd = process.cwd();
const git = simpleGit(cwd);
const exec = util.promisify(childProcess.exec);

async function main() {
  const tag = `v${package.version}`;
  const tags = (await git.tags()).all
  if (tags.includes(tag)) {
    console.log(chalk.yellow(`[ci-tag] warning: ${tag} already existed, please change another tag.`));
    process.exit(0);
  }
  const message = `Version ${package.version}`;
  const { stdout } = await exec(['git', 'remote', '-v'].join(' '));
  const remoteLines = stdout.trim();
  if (remoteLines.includes('lerna-tpl')) {
    console.log(chalk.blue(`[ci-tag] info: start to create ${tag}.`));
    await exec(['git', 'tag', '-a', tag, '-m', `"${message}"`].join(' '));
    await exec(['git', 'push', 'origin', tag].join(' '));
    console.log(chalk.green(`[ci-tag] info: ${tag} already pushed origin successfully.`));
  } else {
    console.log(chalk.red(`[ci-tag] error: unable to find the upstream remote. It should be a remote pointing to "GenesisUILib"`));
    process.exit(0);
  }
}

main();
